<script setup name="Yjfgl">
import { ElDatePicker, ElMessageBox } from 'element-plus'
import { officialFeeSearchConfig, officialFeeTableColumns } from '@/views/system/gfRecord/officialFeeConfig.js'
import { formatDate } from '@/utils/dayjs.js'
import SvgIcon from '@/components/SvgIcon/index.vue'
import businessService from '@/api/business/index.js'
import zlAgencyService from '@/api/finance/zlAgency.js'
import gfJfdService from '@/api/gfJfd/index.js'
import useMessageBox from '@/utils/useMessageBox.js'
import gfRecordService from '@/api/gfRecord/index.js'
import Toolbar from '@/components/Toolbar/Toolbar.vue'
import { useDict } from '@/utils/dict.js'
import { deepClone, tableCheckChane } from '@/utils/index.js'
import 'element-plus/theme-chalk/el-empty.css'
import Message from 'vue-m-message'

const { proxy } = getCurrentInstance()
const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
const ids = ref([])
const tableData = ref([])
const { sys_patent_type, jf_node, jfd_status, gf_record_status } = useDict('sys_patent_type', 'jf_node', 'jfd_status', 'gf_record_status')
const customerList = ref([])
const businessList = ref([])
const tableColumn = reactive([
  {
    type: 'checkbox',
    width: 50,
    align: 'center',
  },
  {
    title: '客户名称',
    field: 'customerName',
    align: 'center',
    minWidth: 90,
  },
  {
    title: '合同编号',
    field: 'contractNumber',
    align: 'center',
  },
  {
    title: '案件编号',
    field: 'patentNumber',
    align: 'center',
  },
  {
    title: '案件名称',
    field: 'patentName',
    align: 'center',
    minWidth: 90,
  },
  // {
  //   title: '业务类型',
  //   field: 'type',
  //   slotName: 'patentType'
  // },
  {
    title: '业务类型',
    field: 'businessName',
    align: 'center',
  },
  {
    title: '缴费节点',
    field: 'jfNode',
    align: 'center',
    slots: {
      default: 'jfNode',
    },
  },
  {
    title: '待缴费用',
    field: 'djMoney',
    align: 'center',
  },
  {
    title: '状态',
    field: 'status',
    align: 'center',
    slots: {
      default: 'status',
    },
  },
  {
    title: '备注',
    field: 'remark',
    align: 'center',
  },
  {
    title: '操作',
    field: 'actions',
    align: 'center',
    slots: {
      default: 'actions',
    },
  },
])
const searchConfig = reactive([
  {
    label: '合同编号',
    type: 'input',
    field: 'contractNumber',
    defaultShow: true,
  },
  {
    label: '客户名称',
    type: 'select',
    field: 'customerId',
    defaultShow: true,
    options: {
      data: customerList,
      label: 'customerName',
      value: 'customerId',
      key: 'customerId',
    },
  },
  {
    label: '案件编号',
    type: 'input',
    field: 'patentNumber',
    defaultShow: true,

  },
  {

    label: '案件名称',
    type: 'input',
    field: 'patentName',
    defaultShow: true,
  },
  {
    label: '业务类型',
    type: 'select',
    options: {
      data: businessList,
      label: 'businessName',
      value: 'businessId',
    },
    field: 'patentType',
  },
  {
    label: '缴费节点',
    type: 'select',
    options: {
      data: jf_node,
    },
    field: 'jfNode',
  },
  {
    label: '备注',
    type: 'input',
    field: 'remark',
  },
])
const queryParam = ref({})

onMounted(() => {
  getList()
})

function handleGenerateAPaymentNote() {
  const idsStr = ids.value.join(',')
  useMessageBox({
    title: '提示',
    description: `是否确认生成这 ${ids.value.length} 条缴费单？`,
    icon: 'color-wait',
  }).then(() => {
    gfJfdService.add(idsStr).then((res) => {
      const code = res.code
      if (code === 200) {
        Message.success('生成缴费单成功')
        ids.value = []
        getList()
      }
    })
  })
}
function getList() {
  const params = {
    ...queryParam.value,
    pageNum: pagerConfig.value.currentPage,
    pageSize: pagerConfig.value.pageSize,
    status: 1,
    confirmStatus: 1,
  }
  gfRecordService.list(params).then((res) => {
    tableData.value = res.rows
    pagerConfig.value.total = res.total
  })
  zlAgencyService.optionList().then((res) => {
    customerList.value = res.data
  })
  businessService.list().then((res) => {
    businessList.value = res.rows
  })
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange(data) {
  ids.value = tableCheckChane(data, 'gfRecordId', ids.value)
}

function handleExport() {
  proxy.download('system/gfRecord/export', { gfRecordIds: ids.value.join(','), ...queryParam.value, status: 1 }, `gfRecord_${new Date().getTime()}.xlsx`)
}

function handleSearch(params) {
  queryParam.value = deepClone(params)
  queryParam.value.beginPaymentTime = params.paymentTime?.[0]
  queryParam.value.endPaymentTime = params.paymentTime?.[1]
  delete queryParam.value.paymentTime
  pagerConfig.value.currentPage = 1
  getList()
}

function handleEditRemark(row) {
  ElMessageBox.prompt('', '修改备注', {
    inputValue: row.remark,
    inputPattern: /^[\s\S]*$/,
    inputErrorMessage: '备注不能为空',
    inputType: 'textarea',
    inputPlaceholder: '请输入备注',
  }).then(({ value }) => {
    const params = {
      ...row,
      remark: value,
    }
    gfRecordService.edit(params).then(() => {
      Message.success('修改备注成功')
      getList()
    })
  })
}

function handlePayByCustomerSelf(data) {
  const idArray = data?.gfRecordId || ids.value.join(',')
  const date = formatDate(new Date())
  const datePicker = h(ElDatePicker, {
    'class': 'w-full!',
    'placeholder': '请选择日期',
    'valueFormat': 'YYYY-MM-DD',
    'modelValue': date,
    'onUpdate:modelValue': (e) => {
      if (datePicker.component?.props) {
        datePicker.component.props.modelValue = e
      }
    },
  })
  ElMessageBox({
    title: '实际缴费时间',
    message: datePicker,
    customClass: 'custom-message-box',
  }).then((res) => {
    if (res === 'confirm') {
      gfRecordService.payByCustomerSelf(idArray, { paymentTime: date }).then((res) => {
        const code = res.code
        if (code === 200) {
          Message.success('提交成功')
        }
      })
    }
  })
}

function handleNoPayMoney(row) {
  ElMessageBox.confirm('是否确认不收取费用？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const gfRecordIds = row?.gfRecordId || ids.value.join(',')
    gfRecordService.noPayMoney(gfRecordIds).then((res) => {
      const code = res.code
      if (code === 200) {
        Message.success('不收取费用成功')
        getList()
      }
    })
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="">
      <SearchBar :search-config="officialFeeSearchConfig" @search="handleSearch" />
    </el-card>
    <el-card shadow="never" class="mt-2">
      <Toolbar>
        <el-button
          v-hasPermi="['system:gfJfd:add']"
          type="primary"
          class="el-gradient-purple"
          :disabled="ids.length === 0"
          @click="handleGenerateAPaymentNote()"
        >
          生成缴费单
          <SvgIcon name="material-symbols-light:order-approve" type="iconify" class="text-[#562DFF] bg-white w-4 h-4 rounded-full ml-2 " />
        </el-button>
        <el-button
          v-hasPermi="['system:gfRecord:payByCustomerSelf']"
          type="primary"
          class="el-gradient-pink"
          :disabled="ids.length === 0"
          @click="handlePayByCustomerSelf()"
        >
          批量客户已缴
          <span class="bg-white w-4 h-4 rounded-full ml-2 ">
            <SvgIcon name="btn-payByCustomerSelf" class-name="text-[#FE1FC4] text-[11px]" />
          </span>
        </el-button>
        <el-button
          v-hasPermi="['system:gfRecord:noPayMoney']"
          type="primary"
          class="el-gradient-primary"
          :disabled="ids.length === 0"
          @click="handleNoPayMoney()"
        >
          不收取费用
          <SvgIcon name="radix-icons:value-none" type="iconify" class="text-[var(--el-color-primary)] bg-white w-4 h-4 rounded-full ml-2 " />
        </el-button>
        <el-button
          v-hasPermi="['system:gfRecord:export']"
          type="warning"
          class="el-gradient-warning"
          @click="handleExport()"
        >
          导出
          <el-icon class="el-icon--right">
            <FolderAdd />
          </el-icon>
        </el-button>
      </Toolbar>
      <vxe-grid
        :row-config="{
          keyField: 'gfRecordId',
        }"
        :data="tableData"
        :columns="officialFeeTableColumns"
        :pager-config="pagerConfig"
        header-cell-class-name="headerCellClass"
        max-height="550px"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
      >
        <template #jfNode="{ row }">
          <dict-tag :options="jf_node" :value="row.jfNode" />
        </template>
        <template #status="{ row }">
          <dict-tag :options="gf_record_status" :value="row.status" type="status" />
        </template>
        <template #actions="{ row }">
          <div class="flex-center">
            <span v-if="row.feeType === '1' || row.feeType === '2'">
              <el-button
                v-hasPermi="['system:gfRecord:payByCustomerSelf']" size="small" text type="primary"
                @click="handlePayByCustomerSelf(row)"
              >
                客户已缴
              </el-button>
              <el-button
                v-hasPermi="['system:gfRecord:noPayMoney']" size="small" text
                type="primary"
                @click="handleNoPayMoney(row)"
              >
                不收取费用
              </el-button>
            </span>
            <el-button
              v-hasPermi="['system:gfRecord:edit']" text type="success" size="small"
              @click="handleEditRemark(row)"
            >
              修改备注
            </el-button>
          </div>
        </template>
      </vxe-grid>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-message-box__message){
  width: 100%;
}
</style>

<style>
.custom-message-box{
  .el-message-box__message{
    width:100%;
  }
}
</style>
